package cxydmmszl.chapter08.t115;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;

/**
 * <li style="color: red;">Prob</li>
 * 转圈打印矩阵
 * <li style="color: green;">Desc</li>
 * 给定一个整型矩阵matrix，请按照顺时针转圈的方式打印它。
 * <li style="color: green;">Input</li>
 * 输入包含多行，第一行两个整数 n 和 m(1≤n,m≤200)，代表矩阵的行数和列数，
 * 接下来 n 行，每行 m 个整数，代表矩阵 matrix(1≤matrix[i][j]≤10^5)。
 * <li style="color: green;">Output</li>
 * 输出一行，包含 n*m 个整数，代表顺时针转圈输出的矩阵 matrix。
 * <li style="color: blue;">Link</li> CD149
 *
 * @author habitplus
 * @since 2021-10-07 16:33
 */
public class Main {
    static StreamTokenizer st =
            new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

    static int nextInt() {
        try {
            st.nextToken();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (int) st.nval;
    }

    public static void main(String[] args) {
        int n = nextInt();
        int m = nextInt();
        int[][] matrix = new int[n][m];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                matrix[i][j] = nextInt();
            }
        }

        printMatrixBySSZ(matrix);
    }

    private static void printMatrixBySSZ(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }

        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;
        StringBuilder sb = new StringBuilder();
        while (top <= bottom && left <= right) {
            if (top == bottom) {
                // 只有一行
                for (int i = left; i <= right; i++) {
                    sb.append(matrix[top][i]).append(" ");
                }
            } else if (left == right) {
                // 只有一列
                for (int i = top; i <= bottom; i++) {
                    sb.append(matrix[i][left]).append(" ");
                }
            } else {
                // 向右
                for (int i = left; i < right; i++) {
                    sb.append(matrix[top][i]).append(" ");
                }
                // 向下
                for (int i = top; i < bottom; i++) {
                    sb.append(matrix[i][right]).append(" ");
                }
                // 向左
                for (int i = right; i > left; i--) {
                    sb.append(matrix[bottom][i]).append(" ");
                }
                // 向上
                for (int i = bottom; i > top; i--) {
                    sb.append(matrix[i][left]).append(" ");
                }
            }
            top++;
            bottom--;
            left++;
            right--;
        }

        System.out.println(sb.toString());
    }
}